package com.zhoug.common.modules.crash;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;


import com.zhoug.common.R;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;

/**
 * 异常列表数据适配器
 * @Author 35574
 * @Date 2020/6/18
 * @Description
 */
class CrashAdapter extends BaseAdapter {
    private List<String> data;

    public CrashAdapter(List<String> data) {
        this.data = data;
    }

    @Override
    public int getCount() {
        if (data != null) {
            return data.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (data != null) {
            return data.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.common_crash_list_item, parent, false);
        }
        TextView tvName = convertView.findViewById(R.id.tv_name);
        TextView tvSize = convertView.findViewById(R.id.tv_size);
        String item = (String) getItem(position);
        File file=new File(item);
        tvName.setText(file.getName());
        tvSize.setText(getFormatSize(file.length()));
        return convertView;
    }

    public static String getFormatSize(long size) {
//        Log.d(TAG, "getFormatSize: size="+size);
        long kb = size / 1024;
        if (kb < 1) {
            return size + "B";
        }

        long mb = kb / 1024;
        if (mb < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kb));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
        }

        long gb = mb / 1024;
        if (gb < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(mb));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }

        long tb = gb / 1024;
        if (tb < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gb));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(tb);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }
}
